<!--
 * @Descripttion: 描述
 * @Author: 刘黎
 * @Date: 2024-06-27 19:40:48
 * @LastEditors: 刘黎
 * @LastEditTime: 2024-08-02 17:32:19
-->
<!-- 新增好友 -->
<template>
  <div class="addNewFriends">
    <!-- 标题 -->
    <div class="pageTitle">朋友圈运营中心</div>
    <div class="queryBox">
      <div class="queryBoxLeft">
        <div class="queryItem">
          <div class="title">任务状态:</div>
          <div class="content">
            <el-select v-model="prop.state" clearable placeholder="请选择任务状态">
              <!-- <el-option
                label="草稿"
                :value="0"/> -->
              <el-option
                label="待执行"
                :value="1"/>
              <el-option
                label="待执中"
                :value="2"/>
              <el-option
                label="执行完成"
                :value="3"/>
            </el-select>
          </div>
        </div>
        <div class="queryItem">
          <div class="title">任务名称:</div>
          <div class="content">
            <el-input v-model="prop.name" placeholder="请输入任务名称"/>
          </div>
        </div>
        <!-- <div class="queryItem">
          <div class="title">任务执行时间:</div>
          <div class="content">
            <el-date-picker
              v-model="prop.time"
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              date-format="YYYY/MM/DD ddd"
              time-format="A hh:mm:ss"
              style="width: 280px;"
            />
          </div>
        </div> -->
      </div>
      <div class="queryBoxRight">
        <el-button type="primary" @click="init">查询</el-button>
        <el-button type="primary" @click="resetClick">重置</el-button>
        <el-button type="success" @click="addClick">新增</el-button>
      </div>
      
    </div>
    <div class="tableClass">
      <el-table :data="tableData" v-loading="loading" border style="width: 100%">
        <el-table-column prop="taskName" label="任务名称" />
        <el-table-column label="任务状态 ">
          <template #default="scope">
            <div v-if="scope.row.taskStatus == 0">草稿</div>
            <div v-if="scope.row.taskStatus == 1">待执行</div>
            <div v-if="scope.row.taskStatus == 2">执行中</div>
            <div v-if="scope.row.taskStatus == 3">执行完成</div>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="labelRemarks" label="任务执行目标" /> -->
        <el-table-column prop="taskNumber" label="数量" />
        <el-table-column label="执行进度 ">
          <template #default="scope">
            {{ scheduleFun(scope.row.sendNumber, scope.row.taskNumber) }}
            <!-- ({{ scope.row.sendNumber }} / {{ scope.row.taskNumber }}).toFixed(2).replace(/\.00$/, '') -->
          </template>
        </el-table-column>
        <el-table-column label="执行时间 ">
          <template #default="scope">
            {{ scope.row.executionTimeStar }}
            <!-- ({{ scope.row.sendNumber }} / {{ scope.row.taskNumber }}).toFixed(2).replace(/\.00$/, '') -->
          </template>
        </el-table-column>
        <!-- <el-table-column prop="number" label="通过率" />
        <el-table-column prop="number" label="重复数量" /> -->
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button v-if="scope.row.taskStatus===0 || scope.row.taskStatus===1" type="danger" size="small" @click="deleteClick(scope.row)">删除</el-button>
            <el-button v-if="scope.row.taskStatus===0 || scope.row.taskStatus===1" type="primary" size="small" @click="editClick(scope.row)">编辑</el-button>
            <el-button v-if="scope.row.taskStatus===2 || scope.row.taskStatus===3" type="primary" size="small" @click="editClick(scope.row, 2)">查看</el-button>
            <el-button v-if="scope.row.taskStatus===0 || scope.row.taskStatus===1" type="primary" size="small" @click="startClick(scope.row)">启动</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="timedPagination">
      <el-pagination
        v-model:current-page="prop.page"
        v-model:page-size="prop.pageSize"
        :total="prop.total"
        background
        layout="prev, pager, next"
        @current-change="handleCurrentChange">
      </el-pagination>
    </div>
    <!-- 新增 -->
    <el-dialog
      v-model="dialogVisible"
      width="528"
      :show-close="false"
      :before-close="dialogClose"
      :destroy-on-close="true"
      :close-on-click-modal="false"
      top="3vh"
      class="departmentDialogClass">
      <template #header="{ close, titleId, titleClass }">
        <div class="my-header">
          <h4 :id="titleId" :class="titleClass">新建添加好友任务</h4>
          <el-icon class="el-icon--left" @click="close"><Close /></el-icon>
        </div>
      </template>
      <div class="content">
        <el-tabs v-model="addForm.timeState" class="demo-tabs">
          <el-tab-pane label="直接执行" :name="1"></el-tab-pane>
          <el-tab-pane label="定时执行" :name="2"></el-tab-pane>
        </el-tabs>
        <el-form :model="addForm" label-width="auto" style="max-width: 600px">
          <el-form-item label="任务名称:">
            <el-input v-model="addForm.taskName" />
          </el-form-item>
          <el-form-item label="验证信息:">
            <el-input v-model="addForm.addComment" />
          </el-form-item>
          <el-form-item label="任务数据导入模板:">
            <el-button type="primary" link  @click="downTemplate('任务数据导入模板.xls')">
              下载导入模板Excel文件
            </el-button>
          </el-form-item>
          <el-form-item label="任务数据导入:">
            <el-upload
              ref="uploadrefss"
              class="upload-demo"
              drag
              action="#"
              accept=".xls,.xslx,.excel,.csv"
              :on-change="uploadChange"
              :auto-upload="false"
              :limit="1"
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                点击或将文件拖拽到这里上传数据
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  支持扩展名:.xslx.excel .csv
                </div>
              </template>
            </el-upload>
          </el-form-item>
          <el-form-item v-if="addForm.timeState===2" label="任务执行时间:">
            <el-date-picker
              v-model="addForm.executionTimeStar"
              type="datetime"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="配置工作号:">
            <el-select v-model="addForm.wxkey" multiple placeholder="请选择发送朋友圈的工作号">
              <el-option
                v-for="item in wxKeyOption"
                :key="item.wxKey"
                :label="item.nickname"
                :value="item.wxKey"/>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <!-- <el-button :loading="loading" type="primary" @click="saveDraftFun(0)">存为草稿</el-button> -->
          <el-button :loading="loading" type="primary" @click="saveFun">保存</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 编辑 -->
    <el-dialog
      v-model="editDialogVisible"
      width="528"
      :show-close="false"
      :before-close="dialogClose"
      :destroy-on-close="true"
      :close-on-click-modal="false"
      top="3vh"
      class="departmentDialogClass">
      <template #header="{ close, titleId, titleClass }">
        <div class="my-header">
          <h4 :id="titleId" :class="titleClass">编辑当前任务·{{ addForm.taskName }}</h4>
          <el-icon class="el-icon--left" @click="close"><Close /></el-icon>
        </div>
      </template>
      <div class="content">
        <h6>任务配置修改:</h6>
        <el-form :model="addForm" label-width="auto" style="max-width: 600px">
          <el-form-item label="任务名称:">
            <el-input v-model="addForm.taskName" />
          </el-form-item>
          <el-form-item label="验证信息:">
            <el-input v-model="addForm.addComment" />
          </el-form-item>
          <el-form-item label="任务执行时间:">
            <el-date-picker
              v-model="addForm.executionTimeStar"
              type="datetime"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-form>
        <h6>任务数据修改:</h6>
        <el-table :data="visibleData" v-loading="loading" border style="width: 100%">
          <el-table-column prop="wxValue" label="任务数据">
            <template #default="scope">
              <el-input v-model="scope.row.wxValue" :disabled="scope.row.isDisabled" />
            </template>
          </el-table-column>
          <el-table-column label="执行日志 ">
            <template #default="scope">
              <div v-if="scope.row.status == 0">未添加</div>
              <div v-if="scope.row.status == 1">成功</div>
              <div v-if="scope.row.status == 2">失败</div>
              <div v-if="scope.row.status == 3">发送成功</div>
              <div v-if="scope.row.status == 4">用户不存在</div>
            </template>
          </el-table-column>
          <el-table-column v-if="!addForm.isLook" label="操作">
            <template #default="scope">
              <el-button type="danger" size="small" @click="visibleDeleteClick(scope.row)">删除</el-button>
              <el-button v-if="scope.row.isDisabled" type="primary" size="small" @click="visibleEditClick(scope.row)">编辑</el-button>
              <el-button v-if="!scope.row.isDisabled" type="primary" size="small" @click="visibleSaveClick(scope.row)">确定</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="!addForm.isLook" :loading="loading" type="primary" @click="saveTaskFun">保存任务</el-button>
        </div>
      </template>
    </el-dialog>
    
  </div>
</template>


<script setup>
import { computed,ref,onMounted } from 'vue'
import { useChatInfoStore, useJobIDStore } from '@/store/index.js'
import { ElMessageBox, ElMessage } from 'element-plus'
import { postApi } from "@/api/api.js"
import moment from 'moment'
let prop = ref({
  state: '',
  name: '',
  time: [],
  page: 1,
  pageSize: 10,
  total: ''
})
let loading = ref(false)
let tableData = ref([])
let chatInfo = computed(() => {
  return useChatInfoStore().chatInfo
})
console.log(chatInfo.value)
function init() { // init初始化执行
  if(chatInfo.value){
    loading.value = true
    let obj = {
      taskName: prop.value.name,
      taskStatus: prop.value.state,
      wxkey: chatInfo.value.wxKey,
      pages: prop.value.page,
      size: prop.value.pageSize
    }
    postApi('/addUser/queryTask', obj).then(res => {
      if(res.code === 200){
        loading.value = false
        tableData.value = res.data.records
        prop.value.total = res.data.total
      }
    }).catch(err => {
      loading.value = false
    })
  }else{
    ElMessageBox.confirm('请先在工作号席位选择登录的工作号').then(() => {})
  }
}
const handleCurrentChange = (val) => {
  prop.value.page = val
  init()
}
function scheduleFun(params, params2) {
  return (params / params2).toFixed(2).replace(/\.00$/, '')
}
function resetClick() { // 重置
  prop.value = {
    state: '',
    name: '',
    time: []
  }
  init()
}
// 删除
function deleteClick(row) {
  ElMessageBox.confirm('确定要删除该条数据吗？','删除').then(() => {
    postApi('/addUser/deletedTask', { id:row.id }).then(res => {
      if(res.code === 200){
        ElMessage({
          message: "操作成功",
          type: 'success'
        })
        init()
      }
    })
  })
}
// 开始执行
function startClick(row) {
  postApi('/addUser/performATask', { id:row.id, wxkey: chatInfo.value.wxKey }).then(res => {
    if(res.code === 200){
      ElMessage({
        message: "操作成功",
        type: 'success'
      })
      init()
    }
  })
}
onMounted(()=>{
  if(chatInfo.value){
    init()
  }
})
let dialogVisible = ref(false)
let editDialogVisible = ref(false)
let addForm = ref({
  timeState: 1, // 1 直接执行， 2定时执行
  addComment: '',
  executionTimeStar: '',
  file: '',
  taskName: '',
  taskStatus: '',
  wxkey: '',
  isLook: false
})
let wxKeyOption = computed(() => {
  console.log(useJobIDStore().JobIDInfo)
  return useJobIDStore().JobIDInfo
})
let uploadrefss = ref('')
function addClick(){
  dialogVisible.value = true
  addForm.value = {
    timeState: 1, // 1 直接执行， 2定时执行
    addComment: '',
    executionTimeStar: '',
    file: '',
    taskName: '',
    taskStatus: '',
    wxkey: ''
  }
  uploadrefss.value.clearFiles()
}
function dialogClose(){
  dialogVisible.value = false
  editDialogVisible.value = false
}
let visibleData = ref([])
let editRows = ref('')
function editClick(rows, type) {
  editRows.value = rows
  if(type==2){
    addForm.value.isLook = true
  }else{
    addForm.value.isLook = false
  }
  editDialogVisible.value = true
  addForm.value.id = rows.id
  addForm.value.addComment = rows.addComment
  addForm.value.taskName = rows.taskName
  addForm.value.wxkey = rows.belongKey
  addForm.value.executionTimeStar = rows.executionTimeStar
  addForm.value.executionTimeEnd = rows.executionTimeEnd
  postApi('/addUser/queryTaskDetails', {
    "taskId": rows.id,
    "wxkey": rows.belongKey
  }).then(res => {
    if(res.code === 200){
      loading.value = false
      res.data.forEach(element => {
        element.isDisabled = true
      })
      visibleData.value = res.data
    }
  }).catch(err => {
    loading.value = false
  })
}
function saveDraftFun(taskStatusType) {
  let executionTimeStar
  if(addForm.value.timeState){
    executionTimeStar = moment().format('YYYY-MM-DD HH:mm:ss'); // 获取当前时间并格式化
  }else{
    executionTimeStar = addForm.value.executionTimeStar
  }
  let taskStatus = taskStatusType ? taskStatusType : 0
  console.log(taskStatus)
  // let obj = {
  //   addComment: addForm.value.addComment,
  //   executionTimeStar: executionTimeStar, // 获取当前时间并格式化,
  //   file: addForm.value.file,
  //   taskName: addForm.value.taskName,
  //   wxkey: addForm.value.wxkey
  // }
  if( addForm.value.wxkey.length > 0 ){
    addForm.value.wxkey.forEach((element,index) => {
      let ossData = new FormData()
      ossData.append('addComment', addForm.value.addComment)
      ossData.append('executionTimeStar', executionTimeStar)
      ossData.append('executionTimeEnd', '2024-07-18 16:16:17')
      ossData.append('taskName', addForm.value.taskName)
      ossData.append('wxkey', element)
      ossData.append('taskStatus', taskStatus)
      ossData.append('file', addForm.value.file)
      
      postApi('/addUser/createAddTask', ossData).then(res => {
        if(res.code === 200){
          if((index+1) === addForm.value.wxkey.length){
            ElMessage({
              message: "操作成功",
              type: 'success',
            })
            dialogVisible.value = false
            init()
          }
        }
      })
    })
  }
}
function saveFun() {
  saveDraftFun(1)
}
function uploadChange(params) {
  console.log(params)
  addForm.value.file = params.raw
  console.log(addForm.value)
}
function downTemplate(name) {
  const url = `${window.location.protocol}//${window.location.host}/template/${name}`
  console.log(url)
  window.open(url, '_blank')
}
// 编辑任务 编辑人
function visibleEditClick(row) {
  row.isDisabled = false
}
function visibleSaveClick(row) {
  postApi('/addUser/queryTaskNumber', {
    id: row.id,
    wxType: row.wxType,
    wxValue: row.wxValue
  }).then(res => {
    if(res.code === 200){
      ElMessage({
        message: "操作成功",
        type: 'success'
      })
      row.isDisabled = true
    }
  })
}
function saveTaskFun() {
  postApi('/addUser/updateTask', {
    id: addForm.value.id,
    addComment: addForm.value.addComment,
    executionTimeEnd: addForm.value.executionTimeEnd,
    executionTimeStar: addForm.value.executionTimeStar,
    taskName: addForm.value.taskName
  }).then(res => {
    if(res.code === 200){
      ElMessage({
        message: "操作成功",
        type: 'success'
      })
      editDialogVisible.value = false
      init()
    }
  })
}
function visibleDeleteClick(row) {
  ElMessageBox.confirm('确定要删除该条数据吗？','删除').then(() => {
    postApi('/addUser/deletedTaskNumber', { id: row.id }).then(res => {
      if(res.code === 200){
        ElMessage({
          message: "操作成功",
          type: 'success'
        })
        editClick(editRows.value)
      }
    })
  })
}
</script>


<style lang="scss" scoped>
.addNewFriends{
  padding: 20px;
  height: 100vh;
  .pageTitle{
    font-weight: 700;
    font-size: 16px;
    color: rgb(16, 16, 16);
  }
  .queryBox{
    background-color: #fff;
    border-radius: 12px;
    padding: 20px;
    margin: 20px 0;
    display: flex;
    justify-content: space-between;
    .queryBoxLeft{
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      .queryItem{
        display: flex;
        align-items: center;
        margin-right: 20px;
        .title{
          font-weight: 400;
          font-size: 14px;
          color: rgb(16, 16, 16);
          margin-right: 10px;
        }
        .content{
          min-width: 194px;
          background-color: rgb(245, 247, 255);
          border-radius: 4px;
          ::v-deep(.el-select__wrapper){
            background-color: transparent;
            box-shadow: 0 0 0;
          }
          ::v-deep(.el-input__wrapper){
            background-color: transparent;
            box-shadow: 0 0 0;
            .el-input__inner{
              text-align: left;
            }
          }

        }
      }
    }
  }
}
.timedPagination{
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}
::v-deep(.departmentDialogClass){
  h6{
    font-size: 12px;
    margin-bottom: 10px;
  }
  .my-header{
    display: flex;
    justify-content: space-between;
    .el-icon--left{
      cursor: pointer;
    }
  }
  .dialog-footer{
    text-align: center;
  }
  .content{
    .addDepartmentClass{
      
      .formItem{
        display: flex;
        align-items: center;
        padding: 10px 15px;
        background-color: #f0f6ff;
        border-radius: 4px;
        margin-bottom: 10px;
        .title{
          font-weight: 400;
          font-size: 14px;
          color: rgb(16, 16, 16);
          margin-right: 10px;
        }
        .elInput{
          flex: 1;
          .el-input__wrapper{
            background-color: transparent;
            box-shadow: none;
          }
        }
        .elSelect{
          flex: 1;
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-left: 10px;
          cursor: pointer;
          padding: 3.5px 0;
          .titles{
            .titles1{
              color: #b5b7ba;
              padding: 3px 0;
            }
            .titles2{
              border-radius: 2px;
              background: rgb(214, 219, 249);
              display: flex;
              align-items: center;
              padding: 4px 6px 5px;
              .titles21{
                font-weight: 400;
                font-size: 12px;
                color: rgba(130,88,255,1);
                margin-right: 5px;
              }
              .titles22{
                font-weight: 400;
                font-size: 12px;
                color: rgba(81,109,255,1);
                margin-right: 15px;
              }
              .titles23{
                display: flex;
                align-items: center;
                cursor: pointer;
              }
            }
          }
          .rotateTrue{
            transition:  0.5s;
            transform: rotate(0);
          }
          .rotateFalse{
            transform: rotate(180deg);
          }
        }
      }
      .administrativeClass{
        border: 2px solid rgb(243, 244, 245);
        border-radius: 4px;
        padding: 0px 10px 10px;
        max-height: 230px;
        overflow-y: auto;
        .administrativeItem{
          &:hover{
            background-color: #d6d8f9;
          }
          display: flex;
          align-items: center;
          border-radius: 4px;
          background-color: rgb(241, 243, 255);
          padding: 10px 10px;
          margin-top: 10px;
          cursor: pointer;
          .avatarClass{
            .image{
              width: 24px;
              height: 24px;
              display: block;
              object-fit: cover;
              border-radius: 50px;
            }
          }
          .name{
            font-weight: 400;
            font-size: 12px;
            color: #101010;
            margin: 0 10px;
          }
          .position{
            font-weight: 400;
            font-size: 12px;
            color: rgb(16, 16, 16);
          }
        }
        .active{
          background-color: #d6d8f9;
        }
      }
    }
  }
}
</style>


